//
//  WBWelcomeView.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 27/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import UIKit

fileprivate let iconHW = screenWidth * 0.3

class WBWelcomeView: UIView {
    
    lazy var iconView: UIImageView = {
        let imageView = UIImageView()
        imageView.wb_setImage(withURLString: userAccountShared.avatar_large!, placeHolder: #imageLiteral(resourceName: "avatar_default_big"))
        return imageView
    }()
    
    lazy var welcomeLabel: UILabel = UILabel(title: "\(userAccountShared.screen_name!)，欢迎回来！YEAH！", fontSize: 17.0, alignment: .center)
    
    override init(frame: CGRect) {
        super.init(frame: mainScreenBounds)
        
        setupUI()
    }
    
    override func didMoveToWindow() {
        addAnimation()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: - Setup methods
extension WBWelcomeView {
    
    fileprivate func setupUI() {
        backgroundColor = globalColorFaded
        
        addSubview(iconView)
        addSubview(welcomeLabel)

        iconView.layer.cornerRadius = iconHW * 0.5
        iconView.layer.masksToBounds = true
        
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(self.snp.top)
            make.size.equalTo(CGSize(width: iconHW, height: iconHW))
        }
        
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        // Makes constraints take effect immediately
        layoutIfNeeded()
    }
    
}

// MARK: - Private methods
extension WBWelcomeView {
    
    fileprivate func addAnimation() {
        iconView.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.snp.top).offset(screenWidth*0.33 + iconHW)
        }
        
        UIView.animate(withDuration: 1.3, delay: 0.7, usingSpringWithDamping: 0.4, initialSpringVelocity: 7.5, options: [], animations: {
            self.layoutIfNeeded()
        }, completion: { (finish: Bool) in
            self.fadeOutAndRemoved()
        })
    }
    
    fileprivate func fadeOutAndRemoved() {
        UIView.animate(withDuration: 0.5, animations: {
            self.alpha = 0.0
        }, completion: { (finish: Bool) in
            self.removeFromSuperview()
        })
    }
    
}
